import http.server
import socketserver
import os
import webbrowser
import threading
import time

# 设置端口为传统的8080端口
PORT = 8080

# 设置前端文件目录
frontend_dir = os.path.join(os.path.dirname(__file__), 'frontend')

# 更改当前工作目录到前端目录
os.chdir(frontend_dir)

# 创建处理器
Handler = http.server.SimpleHTTPRequestHandler

def open_browser():
    """延时打开浏览器，确保服务器已启动"""
    time.sleep(2)  # 等待2秒确保服务器启动
    try:
        webbrowser.open(f'http://localhost:{PORT}')
        print("浏览器已自动打开，请查看页面")
    except Exception as e:
        print(f"无法自动打开浏览器: {e}")

# 创建服务器
with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print(f"前端服务器运行在 http://localhost:{PORT}")
    print("按 Ctrl+C 停止服务器")
    
    # 启动一个线程来打开浏览器
    browser_thread = threading.Thread(target=open_browser)
    browser_thread.daemon = True
    browser_thread.start()
    
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("\n服务器已停止")